const express = require('express')
const router = express.Router()
const fs = require('fs')
const path = require('path')
const multer = require('multer')
const upload = multer({ dest: './files' })
const number = require('../utils/number')
const basePath = '../files'

router.use(express.json())

// 文件上传
router.post('/upload', upload.single('file'), (req, res) => {
  let file = req.file
  // const originalname = file.originalname
  const newFileName = `${number.getRandomNumber(20)}.${file.originalname.split('.').pop()}`
  if (file) {
    fs.renameSync(
      './files/' + file.filename,
      `./files/${newFileName}`
    )
    res.status(200).send({
      msg: '文件上传成功！',
      code: 1,
      data: {
        filename: file.originalname,
        url: path.resolve(__dirname, basePath, newFileName),
        newFileName
      }
    })
  }
  res.status(500).send({
    msg: '文件上传失败，请稍后重试',
    code: 0
  })
});

// 文件下载

module.exports = router